<?php

namespace App\Http\Controllers;

use App\Http\Requests\EditRolesRequest;
use App\MakeTable\Table;
use App\Permission;
use App\Redict\Success;
use App\Role;
use Illuminate\Http\Request;

class RoleController extends Controller
{
    public function index(){
        $pagename = '角色管理';
        $modelurl = 'roles';
        $tablecate = ['tablecate'=>'角色'];
        $headname = ['字段名','角色名','权限','操作'];
        $tablehead = ['name','label','permissions','id'];
        $roletable = new Table($tablehead,$page = 8);
        $model = $roletable->viewdata(Role::class);
        $models = $roletable->viewpagedata(Role::class);
        return view('admin.home.tableshow',compact('tablecate','model','tablehead','models','headname','pagename','modelurl'));
    }
    public function edit($id){
        $modelurl = 'roles';
        $role = Role::findOrFail($id);
        $permissions_list = collect($role->permissions->pluck('id'))->toArray();
        $pagename = $role->name;
        $permissions = Permission::all()->pluck('label','id');

        return view('admin.home.roleedit',compact('pagename','role','permissions','permissions_list','modelurl'));

    }
    public function update(EditRolesRequest $request,$id){

        $role = Role::findOrFail($id);
        $input = $request->input('permissions_list');
        $now = collect($role->permissions->pluck('id'))->toArray();
        $role->permissions()->attach(collect($input)->diff($now)->toArray());
        $role->permissions()->detach(collect($now)->diff($input)->toArray());
        $role->update($request->all());

        return Success::back();
    }
    public function create(){
        $modelurl = 'roles';
        $pagename = '添加角色';
        $permissions = Permission::all()->pluck('label','id');
        return view('admin.home.roleform',compact('pagename','permissions','modelurl'));
    }
    public function store(EditRolesRequest $request){

        $role = Role::create($request->all());
        $role->permissions()->attach($request->input('permissions_list'));

        return redirect('admin/roles')->with('message', '成功添加'.$role->name);
    }
    public function destroy($id){
        Role::destroy($id);
        return Success::back();
    }
}
